<?
class file_browser
{ var $templates=null;
  var $displaydot=false;
  var $template=null;
  var $version="1.3.1";
  var $rootfolder="";
  var $CtlSet="";
  var $urlCtlSet="";
  var $srcFolder="";
  var $urlSrcFolder="";
  function dirsize($directory)
  { $content=opendir($directory);
    $size=0;
    while (($filename=readdir($content))!==false)
    if ($filename!="." && $filename!="..")
    { $path=$directory."/".$filename;
      if (is_dir($path)) $size+=$this->dirsize($path);
      if (is_file($path)) $size+=filesize($path);
    }
    closedir($content);
    return $size;
  }
  
  function NumberFileOfFolder($directory)
  { 
  	$TotalFile=0;
	if(is_dir($directory))
	{
		$dir = opendir($directory); 
		while ( FALSE !== ($file = readdir($dir)) ) 
		{ 
			if (!is_dir($directory."/".$file)) {$TotalFile++;}
		} 
		closedir($dir);
	}
	return $TotalFile;
  }
  
  function bytesize($size)
  { if (empty($size)) return number_format($size, 2)." KB"; $size=$size/1024;
    if ($size < 1024) return number_format($size, 2)." KB";
    elseif ($size / 1024 < 1024) return number_format($size/1024, 2)." MB";
    elseif ($size / 1024 / 1024 < 1024) return number_format($size / 1024 / 1024, 2)." GB";
    else return number_format($size / 1024 / 1024 / 1024, 2)." TB";
  }

  function error($code)
  { switch($code)
    { case 'ERR01': $error='Invalid interface path. Please make a proper call for the File Browser Class.'; break;
      case 'ERR02': $error='Valid interface path but the template you have selected does not exist.'; break;
    }
    if (isset($error))
    { echo '			<table align="center" border="0" cellpadding="0" cellspacing="0" width="780">';
      echo '				<tr>';
      echo '					<td align="left" bgcolor="#BF000D"   height="21" nowrap="nowrap" style="padding-left: 05px; padding-right: 10px"><font face="Tahoma" size=1 style="font-size: 8pt; text-decoration: none;" color="#FFFFFF"><b>Error:</b></font></td>';
      echo '					<td align="left" bgcolor="#BF000D"   width="100%" height="21" nowrap="nowrap" style="padding-left: 05px; padding-right: 10px"><font face="Tahoma" size=1 style="font-size: 8pt; text-decoration: none;" color="#FFFFFF" width="100%"><b>'.$error.'</b></font></td>';
      echo '					<td align="right" bgcolor="#BF000D"  height="21" nowrap="nowrap" style="padding-left: 05px; padding-right: 05px"><font face="Tahoma" size=1 style="font-size: 8pt; text-decoration: none;" color="#FFFFFF"><b>Please fix it.</b></font></td>';
      echo '				</tr>';
      echo '			</table>'; }
    exit;
  }

  function filetypes($extension=null,$advanced=false,$hidden=false)
  { if ($advanced==true)
    { $filetypes[null]="";
      $filetypes['ai']="psd.gif";
      $filetypes['aif']="wmv.gif";
      $filetypes['aiff']="wmv.gif";
      $filetypes['ani']="file.gif";
      $filetypes['ans']="txt.gif";
      $filetypes['arc']="rar.gif";
      $filetypes['arj']="rar.gif";
      $filetypes['asc']="txt.gif";
	  $filetypes['avi']="wmv.gif";
      $filetypes['bmp']="bmp.gif";
      $filetypes['cab']="rar.gif";
      $filetypes['css']="txt.gif";
      $filetypes['cur']="file.gif";
      $filetypes['dat']="wmv.gif";
      $filetypes['doc']="doc.gif";
      $filetypes['exe']="exe.gif";
      $filetypes['gif']="gif.gif";
      $filetypes['gz']="rar.gif";
      $filetypes['hlp']="txt.gif";
      $filetypes['htm']="htm.gif";
      $filetypes['html']="htm.gif";
      $filetypes['ico']="file.gif";
      $filetypes['jpeg']="jpg.gif";
      $filetypes['jpg']="jpg.gif";
      $filetypes['log']="txt.gif";
      $filetypes['mov']="wmv.gif";
      $filetypes['movie']="wmv.gif";
      $filetypes['mp2']="wmv.gif";
      $filetypes['mp3']="wmv.gif";
      $filetypes['mpe']="wmv.gif";
      $filetypes['mpeg']="wmv.gif";
      $filetypes['mpg']="wmv.gif";
      $filetypes['phps']="txt.gif";
	  $filetypes['php']="txt.gif";
      $filetypes['phtml']="htm.gif";
      $filetypes['psd']="psd.gif";
      $filetypes['shtml']="htm.gif";
      $filetypes['txt']="txt.gif";
      $filetypes['wav']="wmv.gif";
	  $filetypes['wmv']="wmv.gif";
      $filetypes['xlm']="xls.gif";
      $filetypes['xls']="xls.gif";
  	  $filetypes['xlt']="xls.gif";
      $filetypes['rar']="rar.gif";
      $filetypes['zip']="rar.gif";
    }
    if ($hidden==true) return "file.gif";
    if (!empty($advanced) && isset($filetypes[$extension]) && !empty($filetypes[$extension])) return $filetypes[$extension];
    else return 'file.gif';
  }

  function row($templates,$type,$path,$title,$adtype,$srcFolder,$rootfolder,$currentfolder)
  { 
  	unset($filename);
    $properties=pathinfo($title); if (!isset($properties['extension'])) $properties['extension']=null;
    if (substr($title,0,1)=='.') $hidden=true; else $hidden=false;
	$rootfolder.=$currentfolder;
	if($currentfolder!="")$currentfolder=$currentfolder."\\";
    switch($title)
    { case '.':  $filename['title']='[.]';
				 $filename['webpath']=$rootfolder;
                 $filename['path']=$path;
                 $filename['type']=(empty($type)?$this->filetypes(strtolower($properties['extension']),$adtype,$hidden):"folder.gif");
                 $filename['size']="--- ---";
                 $filename['icon']="folder";
                 $filename['link']=$_SERVER['PHP_SELF']."?dir=".base64_encode(realpath($path));
                 $filename['update']=date("d/m/Y - H:i:s",filemtime($path."/".$title));
				 $filename['rename']="--- ---";
				 $filename['delete']="--- ---";
                 break;
      case '..': $filename['title']='[..]';
	  			 $filename['webpath']=$rootfolder;
                 $filename['path']=$path;
                 $filename['type']=(empty($type)?$this->filetypes(strtolower($properties['extension']),$adtype,$hidden):"folder.gif");
                 $filename['size']="--- ---";
                 $filename['icon']="folder";
                 $filename['link']=$_SERVER['PHP_SELF']."?dir=".base64_encode(realpath($path.'/'.$title)).$this->urlCtlSet.$this->urlSrcFolder;
                 $filename['update']=date("d/m/Y - H:i:s",filemtime($path."/".$title));
				 $filename['rename']="--- ---";
				 $filename['delete']="--- ---";
                 break;
      default:  $filename['title']=$title; 
      			//$filename['title']="<img src='http://localhost/nama/upload/ads/".$title."' style='width: 200px; height: 80px;' />";
                 $filename['webpath']=$rootfolder;
				 $filename['path']=$path;
                 if (empty($type))
                 { 
                 	$filename['type']=(empty($type)?$this->filetypes(strtolower($properties['extension']),$adtype,$hidden):"Folder");
                   	$filename['size']=$this->bytesize(filesize($path."/".$title));
                   	$filename['icon']="filename";
				   	$flink="";if($this->CtlSet!="")$flink="javascript:SelectFile('".$this->CtlSet."','".str_replace('\\', '/', $currentfolder).$title."');";
                   	$filename['link']=$flink;
                   	$filename['update']=date("d/m/Y - H:i:s",filemtime($path."/".$title));
				   	$filename['rename']="--- ---";
				   	$filename['delete']="--- ---";
                 }
                 else
                 { $filename['type']=(empty($type)?$this->filetypes(strtolower($properties['extension']),$adtype,$hidden):"folder.gif");
                   $filename['size']=$this->bytesize(filesize($path."/".$title));
                   $filename['icon']="folder";
                   $filename['link']=$_SERVER['PHP_SELF']."?dir=".base64_encode(realpath($path.'/'.$filename['title'])).$this->urlCtlSet.$this->urlSrcFolder;
                   $filename['update']=date("d/m/Y - H:i:s",filemtime($path."/".$title));
				   $filename['rename']=$_SERVER['PHP_SELF']."?mode=".base64_encode('renamefolder')."&dir=".base64_encode($path)."&folder=".base64_encode($title).$this->urlCtlSet.$this->urlSrcFolder;
				   $filename['delete']=$_SERVER['PHP_SELF']."?mode=".base64_encode('delfolder')."&dir=".base64_encode($path)."&folder=".base64_encode($title).$this->urlCtlSet.$this->urlSrcFolder;
                 }
                 break;
    }
	if (empty($type))
    	$templates->layout_row($filename);
	else
		$templates->layout_folder($filename);
  }

	function file_browser($interface,$template,$mode=false,$chrooted=false,$adtype=true,$ctlSet="",$srcFolder="")
	{ 
		$chrooted=$chrooted.$srcFolder."/";
		if (!empty($_GET['mode'])) $mode=base64_decode($_GET['mode']);
		$errstr="";
		if($ctlSet!="")	{$this->CtlSet=$ctlSet;$this->urlCtlSet="&ctl=".$ctlSet;}
		if($srcFolder!="")	{$this->srcFolder=$srcFolder;$this->urlSrcFolder="&urlScr=".$srcFolder;}
		if(!is_dir($chrooted))
		{
			if(!mkdir($chrooted,0777)) $Err="Thư mục không tồn tại và bạn không thể tạo thư mục. Hãy kiểm tra.";
			if($Err!="") echo $Err;break;
		}
		$rootfolder=$chrooted;
		foreach(array_map('chr',range(ord('a'),ord('z'))) as $letter) $letters[]=$letter;
		$scans=array('folders'=>array(),'files'=>array());
		if (!is_dir($interface)) $this->error('ERR01');
		if (!include($interface.'/template_'.$template.'.php')) $this->error('ERR02');
		if (empty($directory) && !empty($_GET['dir'])) $directory=base64_decode($_GET['dir']);
		
		if (empty($chrooted) OR !is_dir(realpath($chrooted))) $chrooted=realpath('./'); else $chrooted=realpath($chrooted);
		if (empty($directory)) $directory=$chrooted;
		$directory=realpath($directory);
		if (substr($directory,0,strlen($chrooted))!=$chrooted) $directory=$chrooted;
		if (!empty($select)) $filter=true; else $filter=false;
		if (version_compare("5.0",phpversion())<0) $scan=scandir($directory);
		else { $scanning=opendir($directory); while (false!==($filename=readdir($scanning))) $scan[]=$filename; }
		foreach($scan as $scanned)
		{ if (is_dir($directory."/".trim($scanned))) $inarray="folders"; else $inarray="files";
		  switch($select)
		  { case null: $scans[$inarray][]=trim($scanned); break;
			case "numbers": if (!in_array(strtolower(substr(trim($scanned),0,1)),$letters)) $scans[$inarray][]=trim($scanned); break;
			default: if (strtolower(substr(trim($scanned),0,1))==strtolower($select)) $scans[$inarray][]=trim($scanned); break;
		  }
		}
		$currentfolder=substr($directory,strlen(realpath($rootfolder))+1);
		$manager=$_SERVER['PHP_SELF'].'?dir='.base64_encode(realpath($chrooted)).$this->urlCtlSet.$this->urlSrcFolder;
		$create=$_SERVER['PHP_SELF'].'?mode='.base64_encode("create").'&dir='.base64_encode(realpath($directory)).$this->urlCtlSet.$this->urlSrcFolder;
		$upload=$_SERVER['PHP_SELF'].'?mode='.base64_encode("upload").'&dir='.base64_encode(realpath($directory)).$this->urlCtlSet.$this->urlSrcFolder;
		$delfile=$_SERVER['PHP_SELF'].'?mode='.base64_encode("delfile").'&dir='.base64_encode(realpath($directory)).$this->urlCtlSet.$this->urlSrcFolder;
		$RedirectUrl=$_SERVER['PHP_SELF'].'?dir='.base64_encode(realpath($directory)).$this->urlCtlSet.$this->urlSrcFolder;
		$errstr=$this->action_mode($mode,$RedirectUrl);
		$templates=&new file_browser_templates($interface,$template,$chrooted,$adtype);
		$templates->interface=$interface;
		$templates->TotalFile=$this->NumberFileOfFolder($directory);
		$templates->layout_header();
		
		$templates->layout_manager($manager,$create,$upload);
		if (count($scans['folders'])+count($scans['files'])==0) $templates->layout_nofiles($filter);
		if ($this->displaydot==false) array_shift($scans['folders']);
		if($mode=="create") $templates->layout_create($RedirectUrl,$errstr);
		if($mode=="upload") $templates->layout_upload($RedirectUrl,base64_encode(realpath($directory)));
		if($mode=="renamefolder")$templates->layout_renamefolder(base64_decode($_GET['folder']),$errstr,$RedirectUrl);
		if($mode=="delfolder")$templates->layout_delfolder(base64_decode($_GET['folder']),$errstr);
		$templates->layout_leftstart();
		$templates->layout_current_folder($currentfolder);
		foreach($scans['folders'] as $title) $this->row($templates,true,$directory,$title,$adtype,$this->srcFolder,$this->CtlSet);
		$templates->layout_leftend();
		$templates->layout_rightstart();
		$templates->layout_headings($delfile);
		foreach($scans['files'] as $title) $this->row($templates,false,$directory,$title,$adtype,$srcFolder,$rootfolder,$currentfolder);
		$templates->layout_rightend();
		$templates->layout_footer($directory,$select,$this->version);
	}
  	
	function action_mode($mode,$url)
	{
		$errstr="";
		switch ($mode)
		{
			case "create";
				if(isset($_POST["foldername"]))
				{
					$newFolder=$_POST["foldername"];
					if(trim($newFolder)!="")
					{
						$Folder=base64_decode($_GET['dir']);
						$errstr=$this->create_folder($Folder,$newFolder);
						if($errstr=="") header("Location:".$url);
					}
				}
				break;
			case "delfile";
				$ListFileName=$_POST["chon"];
				$Folder=base64_decode($_GET['dir']);
				$this->delete_file($Folder,$ListFileName);
				header("Location:".$url);
				break;
			case "renamefolder";
				if(isset($_POST["foldername"]))
				{
					$newFolder=$_POST["foldername"];
					
					$oldFolder=base64_decode($_GET['folder']);
					$errstr=$this->rename_folder(base64_decode($_GET['dir']),$oldFolder,$newFolder);
					if($errstr=="") header("Location:".$url);
				}
				break;
			case "delfolder";
				$Folder=base64_decode($_GET['dir']);
				$delFolder=base64_decode($_GET['folder']);
				if($delFolder!="")
				{
					$errstr=$this->delete_folder($Folder,$delFolder);
					if($errstr=="") header("Location:".$url);
				}
				break;
			default:
				break;
		}
		return $errstr;
	}
	
	
	function create_folder($Folder,$newFolder)
	  { 
		$Err="";
		if($this->CheckName($newFolder))
		{
			$mkfolder = $Folder.'/'.$newFolder;
			if(is_dir($mkfolder)) 
				$Err='Tên thư mục <b style="color:#FF0000">'.$newFolder.'</b> đã tồn tại. Chọn tên khác.';
			else
			{
				if(!mkdir($mkfolder,0777)) $Err="Bạn không thể tạo thư mục. Hãy kiểm tra.";
			}
		}
		else $Err="Tên thư mục không hợp lệ.";
		return $Err;
	  }
	
	  function delete_file($folder,$filename)
	  { 
		$sListImgs=split(",",$filename);
		foreach($sListImgs as $sFile)
		{
			$sDel			= $folder."/".$sFile;
			$sDel_thumbs	= $folder."/thumbs/".$sFile;
			if(is_file($sDel)) unlink($sDel);
			if(is_file($sDel_thumbs)) unlink($sDel_thumbs);
		}
	  }
	  
	  function rename_folder($folder,$oldfolder,$newfolder)
	  { 
		$err="";
		if($this->CheckName($newfolder))
		{
			if(is_dir($folder."/".$newfolder)) 
			{	$err='Tên thư mục <b style="color:#FF0000">'.$newfolder.'</b> đã tồn tại. Chọn tên khác.';}
			else
				if(!rename($folder."/".$oldfolder,$folder."/".$newfolder)) $err="Đổi tên không thành công. Xin hãy kiểm tra lại.";
		}
		else $err="Tên thư mục không hợp lệ.";
		return $err;	
	  }
	  
	  function delete_folder($folder,$delfolder)
	  { 
		$err="";
		$_delfolder=$folder."/".$delfolder;
		if(!rmdir($_delfolder)) $err='Không thể xóa thư mục <b style="color:#FF0000">'.$delfolder.'</b> . Thư mục cần xóa phải trống hoặc bạn không có quyền xóa.';
		return $err;
	  }
	  
	  function CheckName($strName)
	  {
		$Check=true;
		$arr1="";
		for($i=97;$i<=122;$i++) $arr1.="'".chr($i)."',";
		for($i=65;$i<=90;$i++) $arr1.="'".chr($i)."',";
		for($i=0;$i<=9;$i++) $arr1.="'".$i."',";
		$arrCheck=$arr1."'_'";
		$strCheck="";
		$len=strlen($strName);
		while($strName!="")
		{
			$strCheck=substr($strName,0,1);
			$strName=substr($strName,1);
			$pos=strpos($arrCheck,$strCheck);
			if ($pos === false) 
			{
				$Check=false;
				break;
			}
		}
		return $Check;
	  }
 }
?>